package com.zhulin.comassistant;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.zl.module.ComBean;
import com.zl.module.util.DataFunc;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android_serialport_api.SerialPort;

/**
 * @author ZL
 */
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView tvMsg;
    private EditText etPortName, etBaudRate, etSend;
    private static String PORT_NAME = "/dev/ttyS3";
    private static int BAUD_RATE = 115200;
    private static OutputStream mOutputStream;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvMsg = findViewById(R.id.tv_msg);
        etPortName = findViewById(R.id.et_port_name);
        etBaudRate = findViewById(R.id.et_baud_rate);
        etSend = findViewById(R.id.et_send);
        findViewById(R.id.btn_open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PORT_NAME = ZViewUtil.getTextViewText(etPortName);
                BAUD_RATE = StringUtil.stringToInt(ZViewUtil.getTextViewText(etBaudRate));
                open();
            }
        });
        findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String msg = ZViewUtil.getTextViewText(etSend);
                sendMessage(DataFunc.HexToByteArr(msg));
            }
        });
    }

    private void showMsg(String msg) {
        if (TextUtils.isEmpty(msg) || null == tvMsg) {
            return;
        }
        String last = null == tvMsg.getText() ? "" : tvMsg.getText().toString();
        if (!TextUtils.isEmpty(msg)) {
            last = last + "\n";
        }
        String show = last + msg;
        ZViewUtil.setTextViewText(tvMsg, show);
    }

    public void open() {
        try {
            SerialPort serialPort = new SerialPort(new File(PORT_NAME), BAUD_RATE, 0);
            InputStream inputStream = serialPort.getInputStream();
            new ReadThread(inputStream).start();
            mOutputStream = serialPort.getOutputStream();
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.i(TAG, ex.getLocalizedMessage());
        }
    }

    public void sendMsg(byte[] msg) {
        sendMessage(msg);
    }

    private void handlePortReceive(ComBean comBean) {
        try {
            String bRec = DataFunc.ByteArrToHex(comBean.bRec);
            String msg = "ComRecData{" + "bRec=" + (StringUtil.isEmpty(bRec) ? "" : bRec.replaceAll(" ", "")) + ", sRecTime='" + comBean.sRecTime + '\'' + ", sComPort='" + comBean.sComPort + '\'' + '}';
            Log.i(TAG, msg);
            showMsg(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.i(TAG, "onDataReceived:" + ex.getMessage());
        }
    }

    private void sendMessage(byte[] msg) {
        if (null == mOutputStream) {
            return;
        }
        try {
            mOutputStream.write(msg);
            mOutputStream.flush();
            showMsg("写入数据：" + DataFunc.ByteArrToHex(msg));
            Log.i(TAG, "写入数据：" + DataFunc.ByteArrToHex(msg));
        } catch (IOException e) {
            e.printStackTrace();
            showMsg("写入数据异常");
            Log.i(TAG, "写入数据异常");
        }
    }

    private class ReadThread extends Thread {
        private InputStream inputStream;

        public ReadThread(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public void run() {
            super.run();
            showMsg("开始接收数据");
            Log.i(TAG, "开始接收数据");
            while (true) {
                try {
                    if (inputStream != null && inputStream.available() > 0) {
                        byte[] buffer = new byte[inputStream.available()];
                        int size = inputStream.read(buffer);
                        ComBean ComRecData = new ComBean(PORT_NAME, buffer, size);
                        handlePortReceive(ComRecData);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    showMsg("接收数据异常");
                    Log.i(TAG, "接收数据异常");
                }
            }
        }
    }

}
